<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Dish extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'category_id',
        'creator_id',
        'menu_id',
        'source_dish_id',
        'dish_source',
        'is_public',
        'image',
        'tags',
        'flavors',
        'cooking_time',
        'is_available',
        'is_featured',
        'sort_order',
        'view_count',
        'order_count',
    ];

    protected $casts = [
        'tags' => 'array',
        'flavors' => 'array',
        'is_available' => 'boolean',
        'is_featured' => 'boolean',
        'is_public' => 'boolean',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 收藏此菜品的用户
     */
    public function favoritedBy(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_favorites');
    }

    /**
     * 菜品分类关系（一对多）
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * 菜品创建者
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'creator_id');
    }

    /**
     * 关联菜单
     */
    public function menu(): BelongsTo
    {
        return $this->belongsTo(Menu::class);
    }

    /**
     * 来源菜品
     */
    public function sourceDish(): BelongsTo
    {
        return $this->belongsTo(Dish::class, 'source_dish_id');
    }


    /**
     * 增加浏览次数
     */
    public function incrementViewCount(): void
    {
        $this->increment('view_count');
    }

    /**
     * 增加点餐次数
     */
    public function incrementOrderCount(): void
    {
        $this->increment('order_count');
    }

    /**
     * 按分类获取菜品（新版本）
     */
    public function scopeByCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    /**
     * 按分类名称获取菜品（兼容旧版本）
     */
    public function scopeByCategoryName($query, string $categoryName)
    {
        return $query->whereHas('category', function ($q) use ($categoryName) {
            $q->where('name', $categoryName);
        });
    }

    /**
     * 按分类标识获取菜品
     */
    public function scopeByCategorySlug($query, string $categorySlug)
    {
        return $query->whereHas('category', function ($q) use ($categorySlug) {
            $q->where('slug', $categorySlug);
        });
    }

    /**
     * 获取可用菜品
     */
    public function scopeAvailable($query)
    {
        return $query->where('is_available', true);
    }

    /**
     * 获取推荐菜品
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }


    // 按辣度筛选功能暂时移除，因为当前迁移文件中没有 spiciness_level 字段

    /**
     * 搜索菜品
     */
    public function scopeSearch($query, string $keyword)
    {
        return $query->where(function ($q) use ($keyword) {
            $q->where('name', 'like', "%{$keyword}%")
              ->orWhere('description', 'like', "%{$keyword}%")
              ->orWhereJsonContains('tags', $keyword);
        });
    }

    /**
     * 作用域：系统菜品
     */
    public function scopeSystem($query)
    {
        return $query->where('dish_source', 'system');
    }

    /**
     * 作用域：用户菜品
     */
    public function scopeUser($query)
    {
        return $query->where('dish_source', 'user');
    }

    /**
     * 作用域：菜单菜品
     */
    public function scopeMenu($query)
    {
        return $query->where('dish_source', 'menu');
    }

    /**
     * 作用域：公开菜品
     */
    public function scopePublic($query)
    {
        return $query->where('is_public', true);
    }

    /**
     * 作用域：按创建者
     */
    public function scopeByCreator($query, int $creatorId)
    {
        return $query->where('creator_id', $creatorId);
    }

    /**
     * 作用域：按菜单
     */
    public function scopeByMenu($query, int $menuId)
    {
        return $query->where('menu_id', $menuId);
    }
}